package ru.alexo.whiskey.events;

import java.io.IOException;
import java.io.OutputStream;

import ru.alexo.whiskey.Midi;
import ru.alexo.whiskey.util.TonesHelper;

/**
 * Event representing a single polyphonic note.
 * 
 * @author Exaybachay
 */
public final class ChordEvent extends MusicEvent {

    private final byte[] codes;

    /**
     * Creates a note event with specified velocity (volume), duration and code
     * 
     * @param velocity
     *            volume of the note
     * @param duration
     *            duration
     * @param codes
     *            codes of the notes in a chord. Use {@link TonesHelper} for
     *            reference.
     */
    public ChordEvent(byte velocity, byte duration, byte... codes) {
	super(velocity, duration);
	if (codes.length > 6) {
	    throw new IllegalArgumentException("Can't support more than 6 voices");
	}
	this.codes = codes;
    }

    @Override
    public int serializeToStream(OutputStream dos, int offset) throws IOException {
	int durat = (4 * Midi.DEFAULT_TPQ / duration);

	for (int i = 0; i < codes.length; i++) {
	    sendLength(offset, dos);
	    dos.write(NOTE_ON);
	    dos.write(codes[i]);
	    dos.write(DEFAULT_VOLUME);

	    offset = 0;
	}

	for (int i = 0; i < codes.length; i++) {
	    sendLength(durat, dos);
	    dos.write(NOTE_OFF);
	    dos.write(codes[i]);
	    dos.write(DEFAULT_VOLUME);

	    durat = 0;
	}

	return 0;
    }

}
